package cz.vutbr.fit.xzemko01.tfmcbs.diagram.extensions.validators;

import java.util.List;

import cz.vutbr.fit.xzemko01.tfmcbs.model.Container;
import cz.vutbr.fit.xzemko01.tfmcbs.model.Interface;
import cz.vutbr.fit.xzemko01.tfmcbs.model.Provider;
import cz.vutbr.fit.xzemko01.tfmcbs.model.ProvidingPort;
import cz.vutbr.fit.xzemko01.tfmcbs.model.Realization;
import cz.vutbr.fit.xzemko01.tfmcbs.model.SimpleComponent;

public class RealizationLinkTargetEndValidator {
	public static boolean validate(Container container, Realization realization, Provider provider, Interface _interface) {
		if(provider == null || _interface == null) {
			return false;
		}
		
		return validateProviderAndInterfaceAreInSameContainer(provider, _interface)
				&& validateProviderNotRealizateInterface(provider, _interface);
	}
	
	private static boolean validateProviderAndInterfaceAreInSameContainer(Provider provider, Interface _interface) {
		Container requierContainer = null;
		if(provider instanceof ProvidingPort) {
			ProvidingPort port = (ProvidingPort) provider;
			if(port.getComponent() != null) {
				requierContainer = port.getComponent().getContainer();
			}
		} else if(provider instanceof SimpleComponent) {
			requierContainer = ((SimpleComponent) provider).getContainer();
		}
		
		return _interface.getContainer() == requierContainer;
	}
	
	private static boolean validateProviderNotRealizateInterface(Provider provider, Interface _interface) {
		List<Realization> realizationList = provider.getRealizations();
		if(realizationList == null) {
			return true;
		}
		
		for(Realization realization : realizationList) {
			if(realization != null && realization.getInterface() == _interface) {
				return false;
			}
		}
		return true;
	}
}
